/**
 * AccessUtils.java - 2011-7-8
 *
 * 版权所有(C)，中国银联股份有限公司，2011，所有权利保留。
 *
 * 项目名称: ums-portal
 * 
 * 修改历史:
 * =============================================================================
 *   修改人			日期								描述
 *   ------------ ---------- ---------------------------------------------------
 *        
 * =============================================================================
 */
package com.aeky.simple.util;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * IP地址访问过滤工具类。
 * 
 * @author wanghui
 * 
 */
public class AccessUtils {
    private static final String[] HTTP_HEADER_IP_ADDRESS_ALL = {
            "Cdn-Src-Ip", "x-forwarded-for", "Proxy-Client-IP", "WL-Proxy-Client-IP" };

    private static final Logger logger = LoggerFactory.getLogger(AccessUtils.class);

    /**
     * 记录请求的ip地址到日志文件中
     * 
     * @param resource
     *            记录ip地址的对象
     * @param request
     *            客户端请求对象
     */
    public static void logIp(Object resource, HttpServletRequest request) {
        logIp(resource.getClass().getName(), request);
    }

    /**
     * 记录请求的ip地址到日志文件中
     * 
     * @param resource
     *            记录ip地址的对象的名称字符串
     * @param request
     *            客户端请求对象
     */
    public static void logIp(String resource, HttpServletRequest request) {
        logger.info("{}:ipAddress=[{}]", resource,
                        getIpAddress(request, HTTP_HEADER_IP_ADDRESS_ALL));
    }

    /**
     * 验证Request 的IP是否在IP Set中
     * 
     * @param request
     *            HttpServletRequest
     * @param allowIPSet
     *            IP Set 可包含：131.252.85.189, 131.252.85.*, 131.252.*. etc.
     * @return 通过验证返回true
     */
    public static boolean ipAllowed(HttpServletRequest request, Set<String> allowIPSet) {
        String ip = getIpAddress(request, HTTP_HEADER_IP_ADDRESS_ALL);
        if (allowIPSet.contains(ip))
            return true;
        int pos = ip.lastIndexOf('.');
        if (pos <= 0)
            return false;
        String subIp = ip.substring(0, pos);
        if (allowIPSet.contains(subIp + ".*"))
            return true;
        pos = subIp.lastIndexOf('.');
        if (pos <= 0)
            return false;
        subIp = subIp.substring(0, pos);
        return allowIPSet.contains(subIp + ".*");
    }

    /**
     * 获取Request IP地址
     * 
     * @param request
     *            HttpServletRequest
     * @return 返回IP地址，如果找不到则返回""。
     */
    public static String getClientIp(HttpServletRequest request) {
        return getIpAddress(request, HTTP_HEADER_IP_ADDRESS_ALL);
    }

    private static String getIpAddress(HttpServletRequest request, String[] ipHeaders) {
        if (null == request || ipHeaders == null) {
            return null;
        }

        String ip = null, src_key = null;

        for (String key : ipHeaders) {
            ip = request.getHeader(key);
            if (StringUtils.isNotBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
                src_key = key;
                break;
            }
        }
        // default
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            src_key = "RemoteAddr";
        }

        return ip == null ? "" : ip.split(",")[0];
    }

}
